import React, {useEffect, useRef, useState} from "react";
import {Howl} from "howler";
import styles from "./index.less"
import {randomKey} from "@/common/utls/randomKey";
import MusicProgressBar from "@/common/components/ZmMusicPlayer/components/MusicProgressBar";

type PlayerIconType = {
    icon: string,
    className?: Array<string>,
    click?: () => void
}
export type musicArrayType = {
    title: string,
    musicObj: Howl,
    author?: string,
    isBindEndEvent: boolean,
    isBindPlay: boolean,
}
let activeMusicArrayId = 0;
const musicArray: Array<musicArrayType> = [
    {
        title: "如果相遇", musicObj: new Howl({
            src: [require("../../../../public/music/one.mp3")],
            autoplay: false,
        }),
        author: "江小北",
        isBindEndEvent: false,
        isBindPlay: false,
    },
    {
        title: "你的凌晨我的黄昏", musicObj: new Howl({
            src: [require("../../../../public/music/two.mp3")],
            autoplay: false,
        }),
        author: "JINBAO",
        isBindEndEvent: false,
        isBindPlay: false,
    }, {
        title: "和宇宙的温柔关联", musicObj: new Howl({
            src: [require("../../../../public/music/three.mp3")],
            autoplay: false,
        }),
        author: "房东的猫",
        isBindEndEvent: false,
        isBindPlay: false,
    },
]
const ZmMusicPlayer = () => {
    const [musicState, setMusicState] = useState<boolean>(true)
    const [activeMusicObj, setActiveMusicObj] = useState<musicArrayType>()
    const [musicTitleScrollClassName, setMusicTitleScrollClassName] = useState<string>()
    const musicTitleRef = useRef<HTMLDivElement>(null)
    const musicTitleBoxRef = useRef<HTMLDivElement>(null)
    let timer: NodeJS.Timeout;
    useEffect(() => {
        if (typeof musicState === "undefined") return;
        generateMusicTitleScrollClassName();
        if (musicState) {
            saveActiveMusicObj();
            musicArray[activeMusicArrayId].musicObj.play()
            return;
        }
        musicArray[activeMusicArrayId].musicObj.pause();
    }, [musicState]);
    const changeMusic = (val: string) => {
        musicArray[activeMusicArrayId].musicObj.pause();
        setMusicTitleScrollClassName("")
        generateMusicTitleScrollClassName();
        switch (val) {
            case ("next"):
                if (activeMusicArrayId + 1 > musicArray.length - 1) {
                    activeMusicArrayId = 0;
                    break;
                }
                activeMusicArrayId++;
                break;
            case ("previous"):
                if (activeMusicArrayId - 1 < 0) {
                    activeMusicArrayId = musicArray.length - 1;
                    break;
                }
                activeMusicArrayId--;
                break;
        }
        musicArray[activeMusicArrayId].musicObj.seek(0);
        saveActiveMusicObj()
        if (musicState) {
            musicArray[activeMusicArrayId].musicObj.play();
        }
    }
    const saveActiveMusicObj = () => {
        setActiveMusicObj(musicArray[activeMusicArrayId]);
        if (!musicArray[activeMusicArrayId].isBindEndEvent) {
            musicArray[activeMusicArrayId].musicObj.on("end", () => {
                musicArray[activeMusicArrayId].isBindEndEvent = true;
                changeMusic("next")
            })
        }
    }
    const initPlayerIcon = () => {
        const iconArray: Array<PlayerIconType> = [
            {icon: "icon-shangyishoushangyige", className: ["icon-common"], click: changeMusic.bind(this, "previous")},
            {
                icon: musicState ? "icon-24gl-pause2" : "icon-24gl-play",
                className: ["icon-common"],
                click: () => setMusicState(!musicState)
            },
            {icon: "icon-xiayigexiayishou", className: ["icon-common"], click: changeMusic.bind(this, "next")}]
        const node: Array<React.ReactNode> = []
        iconArray.forEach(item => {
            let temp: string = "";
            if (item.className) {
                item.className.forEach(item => {
                    temp = `${temp} ${styles[item]}`
                })
            }
            let classNameStr = temp ? `${temp} iconfont ${item.icon}` : ` iconfont ${item.icon}`;
            node.push(<span className={classNameStr} key={randomKey()} onClick={item.click}></span>)
        })
        return node
    }
    const generateMusicTitleScrollClassName = () => {
        if (timer) clearTimeout(timer)
        if (musicState) {
            timer = setTimeout(() => {
                if (musicTitleBoxRef.current?.clientWidth && musicTitleRef.current?.clientWidth && musicTitleRef.current?.scrollWidth > musicTitleBoxRef.current?.clientWidth) {
                    setMusicTitleScrollClassName(styles["music-title-scroll"])
                }
            }, 1000)
        } else {
            setMusicTitleScrollClassName(" ")
        }
    }
    const seekMusic = (val: number) => {
        activeMusicObj?.musicObj.seek(val);
    }
    return <>
        <div className={styles["player-container"]}>
            <div className={styles["player-header"]} style={{height: musicState ? "60px" : "0px"}}>
                <div className={styles["music-title-box"]} ref={musicTitleBoxRef}>
                    <div ref={musicTitleRef}
                         className={`${styles["music-title"]} ${musicTitleScrollClassName}`}
                    >{activeMusicObj?.title}</div>
                </div>
                <div className={styles["music-author"]}>{activeMusicObj?.author}</div>
                <MusicProgressBar musicObj={activeMusicObj} seekMusic={seekMusic}></MusicProgressBar>
            </div>
            <div className={styles["player-control"]}>
                <div
                    className={musicState ? `${styles["player-face"]} ${styles["player-face-animation"]}` : styles["player-face"]}></div>
                {initPlayerIcon()}
            </div>
        </div>
    </>
}
export default ZmMusicPlayer;